package com.dragon.utilslibrary.tools;

import java.io.UnsupportedEncodingException;
import java.nio.ByteOrder;
import java.nio.charset.Charset;
import java.util.Locale;

public class SdkUtils {

    private static final String TAG = "SdkUtils";

    public static String byteArrayToHexString(byte[] bytes) {
        if (null != bytes) {
            StringBuilder sb = new StringBuilder(bytes.length * 2);
            for (int i = 0; i < bytes.length; i++) {
                if ((bytes[i] & 0xff) < 0x10) {
                    sb.append('0');
                }
                sb.append(Integer.toHexString(0xff & bytes[i]));
                if (i != bytes.length - 1) {
                    sb.append(" ");
                }
            }
            return sb.toString();
        } else {
            LogUtils.i(TAG, "null == bytes");
        }

        return null;
    }

    /**
     * 将字符串数据取整（即去除尾部的无效数据）后返回
     *
     * @param data
     * @return
     */
    public static byte[] stringBytesUTF_8_ToCeil(byte[] data) {
        if (null != data) {
            byte[] result = data;
            int len = data.length;
            do {
                String tmp = SdkUtils.byteToString_UTF_8(result);
                result = tmp.substring(0, tmp.length() - 1).getBytes(Charset.forName("UTF-8"));
            } while (result.length >= len);
            return result;
        }
        return null;
    }

    public static byte[] hexStringToByteArray(String source) {
        source = source.trim().toLowerCase(Locale.getDefault());
        if (source.startsWith("0x")) {
            source = source.substring(2, source.length());
        }

        int length = source.length() / 2;
        byte[] message = new byte[length];

        for (int i = 0; i < length; i++) {
            int shi = hexToInt(source.charAt(2 * i));
            int ge = hexToInt(source.charAt(2 * i + 1));
            if (shi < 0 || ge < 0) {
                return null;
            }
            message[i] = (byte) (shi * 16 + ge);
        }
        return message;
    }

    private static int hexToInt(char hex) {
        int result;
        if (('0' <= hex && hex <= '9')) {
            result = hex - 48;
        } else if (('a' <= hex && hex <= 'f')) {
            result = hex - 87;

        } else if ('A' <= hex && hex <= 'F') {
            result = hex - 55;
        } else {
            result = -1;
        }

        return result;
    }

    /**
     * 字符串转换成utf-8编码字节数组
     *
     * @param source
     * @return
     */
    public static byte[] StringToByte_UTF_8(String source) {
        byte[] mesage = null;
        try {
            mesage = source.getBytes("utf-8");
            LogUtils.d("StringToByte_UTF_8", byteArrayToHexString(mesage));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return mesage;
    }

    /**
     * uft-8字节数组转换成字符串
     *
     * @param source
     * @return
     */
    public static String byteToString_UTF_8(byte[] source) {
        String teString = null;
        try {
            teString = new String(source, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        LogUtils.d("StringToByte_UTF_8", teString);
        return teString;
    }

    /**
     * short 类型转换成byte[]
     *
     * @param number
     * @return
     */
    public static byte[] shortToByteArray(short number) {
        byte[] arr = new byte[2];
        arr[0] = (byte) (number / 256);
        arr[1] = (byte) (number % 256);

        return arr;
    }

    /**
     * 十六进制byte数组转化成十进制字符串 如 {0xf, 0x2, 0x8, 0xc} 转化成"15020812"
     *
     * @param bytes
     * @return 转化后的字符串
     */
    public static String hexByteArrayToDexString(byte[] bytes) {
        if (null != bytes) {
            StringBuffer sb = new StringBuffer(bytes.length * 2);
            for (int i = 0; i < bytes.length; i++) {
                if ((bytes[i] & 0xff) < 0xa) {
                    sb.append('0');
                }
                sb.append(bytes[i] + "");
            }
            return sb.toString();
        }
        return null;
    }

    /**
     * For example,<I> byte[] data = {0x56, 0x4B, 0xEB, 0x32} </I>, then the result is <I>int res = 0x564BEB32</I>
     *
     * @param data
     * @return
     */
    public static int bytesToInt(byte[] data) {
        return bytesToInt(data, 0);
    }

    /**
     * For example,<I> byte[] data = {0x56, 0x4B, 0xEB, 0x32} </I>, then the result is <I>int res = 0x564BEB32</I>
     *
     * @param data
     * @param startPos
     * @return
     */
    public static int bytesToInt(byte[] data, int startPos) {
        return bytesToInt(data, startPos, data.length - startPos);
    }

    /**
     * For example,<I> byte[] data = {0x56, 0x4B, 0xEB, 0x32} </I>, then the result is <I>int res = 0x564BEB32</I>
     *
     * @param data
     * @param startPos
     * @param len
     * @return
     */
    public static int bytesToInt(byte[] data, int startPos, int len) {
        return bytesToInt(data, startPos, len, ByteOrder.BIG_ENDIAN);
    }

    /**
     * If {@code order == ByteOrder.LITTLE_ENDIAN}, the result is for this instance:<br>
     * <I> byte[] data = {0x32, 0xEB, 0x4B, 0x56} </I>, then the result is <I>int res = 0x564BEB32</I>
     *
     * @param data
     * @param startPos
     * @param len
     * @param order
     * @return
     */
    public static int bytesToInt(byte[] data, int startPos, int len, ByteOrder order) {
        if (len > 4) {
            throw new RuntimeException("The length of byte array you want to convert to int is greater than 4: len=" + len);
        }

        int iOutcome = 0;
        if (order == ByteOrder.BIG_ENDIAN) {
            for (int i = 0; i < len; i++) {
                iOutcome = (iOutcome << 8) | (data[startPos + i] & 0x000000ff);
            }
        } else {
            for (int i = 0; i < len; i++) {
                iOutcome = iOutcome | ((data[startPos + i] & 0x000000ff) << i * 8);
            }
        }
        return iOutcome;
    }

    /**
     * 将int类型的数据转换为byte数组
     *
     * @param n int数据
     * @return 生成的byte数组
     */
    public static byte[] intToBytes(int n) {
        String s = String.valueOf(n);
        return s.getBytes();
    }

    public static byte[] intToByteArray1(int i) {
        byte[] result = new byte[4];
        result[0] = (byte) ((i >> 24) & 0xFF);
        result[1] = (byte) ((i >> 16) & 0xFF);
        result[2] = (byte) ((i >> 8) & 0xFF);
        result[3] = (byte) (i & 0xFF);
        return result;
    }

    /**
     * mac地址加
     *
     * @param mac   (00:00:00:00:00:00)
     * @param plush 加上多少
     * @return
     */
    public static String macPlus(String mac, int plush) {
        String substring = mac.substring(15, mac.length());
        byte[] bytes = SdkUtils.hexStringToByteArray(substring);
        byte[] b = new byte[1];
        b[0] = (byte) ((bytes[0] + plush) % 256);
        String s = SdkUtils.byteArrayToHexString(b);
        String newMac = mac.substring(0, 15);
        newMac = newMac + s;
//      mac = mac.replace(":", "");
//		long macValue = Long.parseLong(mac, 16) + plush;
//		byte[] addMac = long2Bytes(macValue);
//		String tmpMac = SdkUtils.byteArrayToHexString(new byte[]{addMac[2],addMac[3],addMac[4],addMac[5],addMac[6],addMac[7]});
//		tmpMac = tmpMac.replace(" ", ":");
        return newMac;
    }

    /**
     * mac地址减
     *
     * @param mac   (00:00:00:00:00:00)
     * @param minus 减去多少
     * @return
     */
    public static String macMinus(String mac, int minus) {
        String substring = mac.substring(15, mac.length());
        byte[] bytes = SdkUtils.hexStringToByteArray(substring);
        byte[] b = new byte[1];
        b[0] = (byte) ((bytes[0] - minus) % 256);
        String s = SdkUtils.byteArrayToHexString(b);
        String newMac = mac.substring(0, 15);
        newMac = newMac + s;
//		mac = mac.replace(":", "");
//		long macValue = Long.parseLong(mac, 16) - minus;
//		byte[] addMac = long2Bytes(macValue);
//		String tmpMac = SdkUtils.byteArrayToHexString(new byte[]{addMac[2],addMac[3],addMac[4],addMac[5],addMac[6],addMac[7]});
//		tmpMac = tmpMac.replace(" ", ":");
        return newMac;
    }

    public static byte[] long2Bytes(long num) {
        byte[] byteNum = new byte[8];
        for (int ix = 0; ix < 8; ++ix) {
            int offset = 64 - (ix + 1) * 8;
            byteNum[ix] = (byte) ((num >> offset) & 0xff);
        }
        return byteNum;
    }

    public static long bytes2Long(byte[] byteNum) {
        long num = 0;
        for (int ix = 0; ix < 8; ++ix) {
            num <<= 8;
            num |= (byteNum[ix] & 0xff);
        }
        return num;
    }

    /**
     * 将10进制转成16进制
     * 大端
     * @param x
     * @return
     */
    public static byte[] long10To16(long x){
        String hex = Long.toHexString(x);
        if(hex.length() % 2 == 1){
            hex = "0"+hex;
        }
        byte[] bytes = hexStringToByteArray(hex);
        return bytes;
    }

    public static byte[] int10To16(int x){
        String hex = Integer.toHexString(x);
        if(hex.length() % 2 == 1){
            hex = "0"+hex;
        }
        byte[] bytes = hexStringToByteArray(hex);
        return bytes;
    }
    /**
     * 把16进制byte转10进制long
     * 大端
     * @param bytes
     * @return
     */
    public static long bytes16To10(byte[] bytes){
        String hex = byteArrayToHexString(bytes).replace(" ", "");
        return Long.parseLong(hex, 16);
    }

    /**
     * 把16进制byte转10进制long
     * 大端
     * @param bytes
     * @return
     */
    public static int int16To10(byte[] bytes){
        String hex = byteArrayToHexString(bytes).replace(" ", "");
        return Integer.parseInt(hex, 16);
    }
    /**
     * bite 转byte
     * @param bit
     * @return
     */
    public static byte bitToByte(String bit) {
        int re, len;
        if (null == bit) {
            return 0;
        }
        len = bit.length();
        if (len != 4 && len != 8) {
            return 0;
        }
        if (len == 8) {// 8 bit处理
            if (bit.charAt(0) == '0') {// 正数
                re = Integer.parseInt(bit, 2);
            } else {// 负数
                re = Integer.parseInt(bit, 2) - 256;
            }
        } else {//4 bit处理
            re = Integer.parseInt(bit, 2);
        }
        return (byte) re;
    }
    /**
     * byte转bit
     * @param by
     * @return
     */
    public static String getBit(byte by){
        StringBuffer sb = new StringBuffer();
        sb.append((by>>7)&0x1)
                .append((by>>6)&0x1)
                .append((by>>5)&0x1)
                .append((by>>4)&0x1)
                .append((by>>3)&0x1)
                .append((by>>2)&0x1)
                .append((by>>1)&0x1)
                .append((by>>0)&0x1);
        return sb.toString();
    }
    /**
     * 数组反转
     * @param Array
     * @return
     */
    public static byte[] reverseArray(byte[] Array) {
        byte[] new_array = new byte[Array.length];
        for (int i = 0; i < Array.length; i++) {
            // 反转后数组的第一个元素等于源数组的最后一个元素：
            new_array[i] = Array[Array.length - i - 1];
        }
        return new_array;
    }

    /**
     * 带符号的2字节bytes转short
     * @param datas 2字节bytes，高位在前，低位在后
     * @return
     */
    public static short byte2ToShort(byte[] datas){
        if(datas == null || datas.length != 2)
        {
            return 0;
        }
        return (short) ((datas[0]<<8) + (datas[1]&0xff)) ;
    }


}
